package com.authine.cloudpivot.ext.controller.fun;

import cn.hutool.core.lang.Assert;
import com.authine.cloudpivot.engine.api.model.bizmodel.BizPropertyModel;
        import com.authine.cloudpivot.engine.api.model.organization.UserModel;
        import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
        import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
        import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
        import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
        import com.authine.cloudpivot.ext.service.CloudSqlService;
        import com.authine.cloudpivot.web.api.controller.base.BaseController;
        import com.authine.cloudpivot.web.api.view.ResponseResult;
        import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.web.bind.annotation.RequestBody;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.RestController;

        import java.time.LocalDateTime;
        import java.time.format.DateTimeFormatter;
        import java.util.HashMap;
        import java.util.List;
        import java.util.Map;
        import java.util.Optional;
        import java.util.stream.Collectors;


/**
 * @Author yb
 * @Date 2022/12/26 17:03
 * @Description
 **/

@RestController
@RequestMapping("/public/companyfun")
@Slf4j
public class CompanyFunController extends BaseController {

    @Autowired
    CloudSqlService sqlService;

    @RequestMapping("/validSubmit")
    public ResponseResult validSubmit(@RequestBody Map<String,Object> map){







        return getOkResponseResult("");
    }

    /**
     *  获取公司职能列表数据
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("getCompanyFunList")
    public List getFileInfoBaeList(Integer page, Integer size){

        String schemaCode = "companyFunBase";

        String tableName = getBizObjectFacade().getTableName(schemaCode);

        List<BizPropertyModel> list = getBizPropertyFacade().getListBySchemaCode(schemaCode,true);

        String codes = list.stream().filter(a-> !a.getDefaultProperty()).map(a -> a.getCode()).collect(Collectors.joining(","));

        StringBuilder sql = new StringBuilder("SELECT ").append(codes).append("  from ")
                .append(tableName);

        if (page != null &&  size != null) {
            if (page>0){
                page = (page-1)*size;
            }
            String limit = String.format(" limit %d,%d", page, size);
            sql.append(limit);
        }
        List<Map<String, Object>> mapList = sqlService.getList(sql.toString());

        return mapList;
    }

    /**
     *  公司级职能基础信息 新增 审批流完成后 数据写到基础表-公司职能
     */
    @RequestMapping("addInfoCompanyFunBase")
    public void addInfoCompanyFunBase(String bizId){
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.FunAddNew, bizId);

//        Object pushAllResult = bizObject.get("pushAllResult");


        List<Map<String,Object>> list = (List<Map<String, Object>>) bizObject.get("SheetFunAddNew");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));


        //获取审批人
        String approvalType = (String) list.get(0).get("approvalType");
        String approval = getFileBaseInfoWorkFlowApproval(bizObject, approvalType);


        for (Map<String, Object> map : list) {
            String funNumber = (String) map.get("funNumber");
            String companyNumber = (String) map.get("companyNumberYingshe");

            try {

                Map<String, Object> data = fileInfoBaseMap(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(map);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }

                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.companyFunBase, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("基础表-公司职能  添加成功 ");
                //调用存储过程
                callProcess(id);

            } catch (Exception e) {
                log.info("基础表-公司职能  添加失败 funNumber={},funNumber={}", funNumber,companyNumber);
                log.info(e.getMessage(), e);
            }

        }
    }



    /**
     *  公司级职能基础信息 新增 审批流完成后 数据写到基础表-公司职能
     */
    @RequestMapping("toVoid")
    public void toVoid(String bizId){
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.ComFunVoid, bizId);

//        Object pushAllResult = bizObject.get("pushAllResult");


        List<Map<String,Object>> list = (List<Map<String, Object>>) bizObject.get("SheetComFunVoid");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));


        //获取审批人
        String approvalType = (String) list.get(0).get("approvalType");
        String approval = getFileBaseInfoWorkFlowApproval(bizObject, approvalType);


        for (Map<String, Object> map : list) {
            String funNumber = (String) map.get("funNumber");
            String companyNumber = (String) map.get("companyNumberYingshe");

            try {

                Map<String, Object> data = fileInfoBaseMap(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(map);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }

                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.companyFunBase, data, false);
                model.setSequenceStatus(SequenceStatus.CANCELED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("基础表-公司职能 作废成功 ");
                //调用存储过程
                callProcessToVoid(id);

            } catch (Exception e) {
                log.info("基础表-公司职能  作废失败 funNumber={},funNumber={}", funNumber,companyNumber);
                log.info(e.getMessage(), e);
            }

        }
    }



    /**
     *  调用存储过程
     *  档案类型fid,档案类型,主责公司fid,主责公司,基础代码fid,基础代码,职能fid,职能,序号,档案代码,档案名称,备注,说明,电子版,主责部门fid,主责部门代码,主责岗代码fid,主责岗代码,权限,主责人,审批人(员工号+姓名),审批时间
     *  exec  SyncCorpFileInfo
     * TypeFID nvarchar(100),       ----档案类型fid
     * TypeNumber nvarchar(50),       ----档案类型
     * ComFID nvarchar(100),        ----主责公司fid
     * ComNumber nvarchar(20),        ----主责公司
     * BaseFID nvarchar(100),        ----基础代码fid
     * BaseNumber nvarchar(100),        ----基础代码
     * FunFID nvarchar(100),        ----职能fid  总公司职能
     * FunNumber nvarchar(50),        ----职能
     * Auditor nvarchar(100),        ----审批人(与EAS登录账号保持一致   员工号+空格+姓名 例：02.0012 李四)
     * AuditDate DATETIME            ----审批时间
     * @param bizId
     */
    private void callProcess(String bizId){

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.companyFunBase);
        StringBuilder sql = new StringBuilder("SELECT companyId,funNumber,funname,comFunResDeptId,auditer,auditDate from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}",map);

        //调用存储过程

        String companyId = MapUtils.getString(map,"companyId","");
        String funNumber = MapUtils.getString(map,"funNumber","");
        String funName = MapUtils.getString(map,"funName","");
        String comFunResDeptId = MapUtils.getString(map,"comFunResDeptId","");
        String auditor = MapUtils.getString(map,"auditer","");
        String auditDate = MapUtils.getString(map,"auditDate","");




        log.info("companyId={},funNumber={},auditor={},auditDate={}",companyId,funNumber,auditor,auditDate);

        Assert.isFalse(StringUtils.isEmpty(companyId),"{}不能为空",companyId);
        Assert.isFalse(StringUtils.isEmpty(funNumber),"{}不能为空",funNumber);
        Assert.isFalse(StringUtils.isEmpty(funName),"{}不能为空",funName);
        Assert.isFalse(StringUtils.isEmpty(comFunResDeptId),"{}不能为空",comFunResDeptId);
        Assert.isFalse(StringUtils.isEmpty(auditor),"{}不能为空",auditor);
        Assert.isFalse(StringUtils.isEmpty(auditDate),"{}不能为空",auditDate);

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncComFunctionInfo '%s','%s','%s','%s','%s','%s'",
                companyId,funNumber,funName,comFunResDeptId,auditor,auditDate);

        log.info("\n==========准备调用存储过程:{}",execSql);

        sqlService.execute(CloudSqlService.htEas,execSql);

        log.info("\n=============存储过程执行完成");

    }

    /**
     *  调用存储过程
     *-----公司职能信息作废
     * exec   BranchFunctionVoid
     *    Company   nvarchar(50),      ----公司FID
     *    Number    nvarchar(50),      ----职能代码
     *    Audit r	nvarchar(50)     ----审批人
     * @param bizId
     */
    private void callProcessToVoid(String bizId){

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.companyFunBase);
        StringBuilder sql = new StringBuilder("SELECT funNumber,companyId,auditer from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}",map);

        //调用存储过程


        String funNumber = MapUtils.getString(map,"funNumber","");
        String companyId = MapUtils.getString(map,"companyId","");
        String auditor = MapUtils.getString(map,"auditer","");



        Assert.isFalse(StringUtils.isEmpty(funNumber),"{}不能为空",funNumber);
        Assert.isFalse(StringUtils.isEmpty(companyId),"{}不能为空",companyId);
        Assert.isFalse(StringUtils.isEmpty(auditor),"{}不能为空",auditor);

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].BranchFunctionVoid  '%s','%s','%s'",
                funNumber,companyId,auditor);

        log.info("\n==========准备调用作废存储过程:{}",execSql);

        sqlService.execute(CloudSqlService.htEas,execSql);

        log.info("\n=============作废存储过程执行完成");

    }


    /**
     *  查询审批人,返回  员工号+姓名
     * @param bizObject
     * @param approvalType
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject, String approvalType) {

        String activityCode="Activity15";
        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = activityCode;
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }

        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);


        return new StringBuilder(user.getEmployeeNo()).append(user.getName()).toString();
    }



    /**
     * 判断是否已存在
     * @return
     */
    private String existsBizObject(Map<String,Object> map){

        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.companyFunBase);

        String funNumber = (String) map.get("funNumber");
        String companyNumber = (String) map.get("companyNumberYingshe");

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where  funNumber='").append(funNumber).append("' and companyNumber='")
                .append(companyNumber).append("'");

        Map<String, Object> data = sqlService.getMap(sql.toString());

        return (String) data.get("id");
    }

    /**
     *  转换成云书  基础表-总公司档案 的数据
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String,Object> fileInfoBaseMap(Map<String,Object> map,String auditDate,String auditer){
        Map<String, Object> data = new HashMap<>();
        //公司id
        data.put("companyId",map.get("companyId"));
        //公司代码
        data.put("companyNumber",map.get("companyNumberYingshe"));
        //公司名称
        data.put("companyName",map.get("companyName"));
        //职能代码
        data.put("funNumber",map.get("funNumber"));
        //职能名称
        data.put("funName",map.get("funName"));
        //英文名
        data.put("englishName",map.get("englishName"));
        //助记码
        data.put("memoryCode",map.get("memoryCode"));
        //公司职能总责部门id
        data.put("comFunResDeptId",map.get("comFunResDeptId"));
        //公司职能总责部门代码
        data.put("comFunResDeptNumber",map.get("comFunResDeptNumber"));
        //公司职能总责部门名称
        data.put("comFunResDeptName",map.get("comFunResDeptName"));
        //审批时间
        data.put("auditDate",auditDate);
        //审批人
        data.put("auditer",auditer);

        return data;
    }


}

